package com.asiainfo.iam.service;

import dm.jdbc.filter.stat.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.cert.X509Certificate;
import java.util.HashMap;

@Service

public class HTTPRequestService {
    private final static Logger log = LoggerFactory.getLogger(HTTPRequestService.class);

    /**
     * 创建信任所有证书的HttpsURLConnection
     */
    private HttpsURLConnection createUnsafeConnection(URL url) throws Exception {
        // 创建信任管理器，信任所有证书
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    public X509Certificate[] getAcceptedIssuers() { return null; }
                    public void checkClientTrusted(X509Certificate[] certs, String authType) {}
                    public void checkServerTrusted(X509Certificate[] certs, String authType) {}
                }
        };

        // 创建SSL上下文并初始化
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());

        // 创建HttpsURLConnection并配置
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setSSLSocketFactory(sc.getSocketFactory());
        conn.setHostnameVerifier((hostname, session) -> true); // 禁用主机名验证
        return conn;
    }

    /**
     * 调用远程签名服务API
     */
    public HashMap<String, String> sendHttpRequestQianMing(String b64OriginData) {
        try {
            URL url = new URL("https://172.31.19.198:5001/api/svs/bss/signData");
            HttpsURLConnection conn = createUnsafeConnection(url);

            // 设置请求头和请求体
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setDoOutput(true);

            String jsonInputString = "{\"b64OriginData\": \"" + b64OriginData + "\",\"certAlias\": \"YPDSJ\"}";
            try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
                wr.writeBytes(jsonInputString);
                wr.flush();
            }

            // 读取响应
            StringBuilder response = new StringBuilder();
            try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
            }

            // 解析JSON响应
            JSONObject jsonObj = new JSONObject(response.toString());
            HashMap<String, String> result = new HashMap<>();
            result.put("b64SignedData", jsonObj.getString("b64SignedData"));
            result.put("b64Cert", jsonObj.getString("b64Cert"));
            return result;
        } catch (Exception e) {
            log.error("签名请求失败", e);
            throw new RuntimeException("签名服务调用失败", e);
        }
    }

    /**
     * 调用远程验签服务API
     */
    public long sendHttpRequestYanQian(String b64OriginData, String b64SignedData, String b64Cert) {
        try {
            URL url = new URL("https://172.31.19.198:5001/api/svs/bss/verifySignedData");
            HttpsURLConnection conn = createUnsafeConnection(url);

            // 设置请求头和请求体
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setDoOutput(true);

            String jsonInputString = "{\"b64OriginData\": \"" + b64OriginData + "\",\"certAlias\": \"YPDSJ\"," +
                    "\"b64SignedData\":\"" + b64SignedData + "\",\"b64Cert\":\"" + b64Cert + "\"}";
            try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
                wr.writeBytes(jsonInputString);
                wr.flush();
            }

            // 读取响应
            StringBuilder response = new StringBuilder();
            try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
            }

            // 解析JSON响应
            JSONObject jsonObj = new JSONObject(response.toString());
            return jsonObj.getLong("errorCode");
        } catch (Exception e) {
            log.error("验签请求失败", e);
            throw new RuntimeException("验签服务调用失败", e);
        }
    }
}
